import { LeftOutlined } from "@ant-design/icons"
import { Button, Card, Input, Layout, message } from "antd"
const { Header, Content, Footer } = Layout;
import { useEffect, useRef, useState } from "react";
import ReactQuill from "react-quill"
import './index.less';
import { MessageError } from "@/utils/commonUtils";
import { switchChapterStatusUsingPost } from "@/services/novel-web/chapterController";
import { EnumChapterStatus } from "@/models/constant";
import { history, useLocation } from "@umijs/max";

const Review:React.FC = () => {
  // chapter
  const location = useLocation();
  const [chapter,setChapter] = useState<API.Chapter>({});
  
  const [title, setTitle] = useState<string>('第 章');
  const [text,setText] = useState<string>('');
  // const [novelInfo,setNovelInfo] = useState<any>({});
  
  const readerRef = useRef<ReactQuill>(null);
  const [wordCount, setWordCount] = useState(0);

  const loadText = async (url: string) => {
    if (!url) return;
    try {
      // setLoading(true);
      // TODO: attention: fetch
      const resp = await fetch(url);
      if (!resp.ok) {
        const error: any = new Error("get file error");
        error.name = 'respError';
        error.info = {
          code: resp.status,
          data: null,
          message: "get file error"
        };
        throw error;
      }
      const t = await resp.text();
      setText(t);

    } catch (error) {
      MessageError(error);
      setText('');
    } finally {
      // setLoading(false);
    }
  };

  useEffect(()=>{
    const {data} = location.state as {data: API.Chapter} || {};
    if(data) {
      setChapter(data);
    } else {
      handleBack();
    }
    
    return (()=>{
      location.state = null;
    })
  },[location.state])

  useEffect(()=>{
    setTitle(chapter.title ?? '');
    loadText(chapter.res ?? '');
  },[chapter]);

  useEffect(()=>{
    const quill = readerRef.current?.getEditor();
    if(quill) {
      quill.setText(text);
    }
  },[text]);

  // reader
  const calculateWordCount = (html) => {
    // 去掉空格
    const text = html.replace(/\s/g, ''); // /<[^>]*>/g
    return text.length;
  };
  const onListenTextChange = () =>{
    
    const quill = readerRef.current?.getEditor();
    setWordCount(calculateWordCount(quill?.getText()));
  };

  // back
  const handleBack = ()=>{
    history.push('/admin/review-msgs');
  };

  // Review
  const handleAllow = async () =>{
    try {
      const resp = await switchChapterStatusUsingPost({
        id: chapter.id,
        status: EnumChapterStatus.PUBLISHED,
      })
      if(resp.data) {
        message.success("操作成功");
        handleBack();
      }
    } catch (error) {
      MessageError(error);
    }
  };

  const handleReject = async ()=> {
    try {
      const resp = await switchChapterStatusUsingPost({
        id: chapter.id,
        status: EnumChapterStatus.FAIL,
      })
      if(resp.data) {
        message.success("操作成功");
        handleBack();
      }
    } catch (error) {
      MessageError(error);
    }
  };
  
  return (
    <Layout className="novel-publish-layout">
      <Header className="publish-header">
        <div className="header-content">
          <Button
            className="back-button"
            icon={<LeftOutlined />}
            type="text"
            onClick={() => handleBack()}
          >
          </Button>

          {/* <h2>{novelInfo.name}</h2> */}
          <h2></h2>

          <div className="action-buttons">
            <Button type="primary" onClick={handleAllow}>审核通过</Button>
            <Button type="dashed" onClick={handleReject}>审核不通过</Button>
          </div>
        </div>
      </Header>
      <Layout className="content-layout">
        <Content className="publish-content">

          <Card className="editor-card">

            <Input
              className="title-input"
              variant="borderless"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder='无数据'
            />


            <ReactQuill
              className="custom-quill-editor"
              readOnly={true}
              ref={readerRef}
              onChange={() => onListenTextChange()}
              formats={[]}
              modules={{
                toolbar: false,
              }}
              placeholder="暂无数据"
            />


          </Card>
        </Content>
      </Layout>
      <Footer className='publish-footer'>
        <div className="editor-footer">
          <span className='footer-word-counter'>
            字数: {wordCount}
          </span>
        </div>
      </Footer>
    </Layout>
  );
};

export default Review;